package hz.mobileproject.pda.ui.activity.work;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.ContentSummaryIntentExtra;
import hz.mobileproject.pda.entity.request.Rq_saveEvaluation;
import hz.mobileproject.pda.entity.response.Rp_ContentSummary;
import hz.mobileproject.pda.entity.response.Rp_eduType;
import hz.mobileproject.pda.entity.response.Rp_eduTypeArrList;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.listener.OnSeekBarChangedListener;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.ContentSummaryAdapter;
import hz.mobileproject.pda.ui.adapter.EduUploadPopAdapter;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.ui.view.EduTalkTrackDialog;
import hz.mobileproject.pda.utils.AudioPlayer;
import hz.mobileproject.pda.utils.HttpRqUtils;


@ContentView(R.layout.activity_play_mp3_and_evaluate)
public class PlayMP3AndEvaluateActivity extends BaseActivity {
    @ViewInject(R.id.pb_playMp3)
    private ProgressBar pb_playPrecent;
    @ViewInject(R.id.sb_playMp3)
    private SeekBar sb_playMp3;
    @ViewInject(R.id.iv_play)
    private ImageView iv_play;
    @ViewInject(R.id.iv_pause)
    private ImageView iv_pause;
    @ViewInject(R.id.tv_curPlayTime)
    private TextView tv_curPlayTime;
    @ViewInject(R.id.tv_durationTime)
    private TextView tv_durationTime;
    @ViewInject(R.id.elv_content_summary)
    private ExpandableListView elv_content_summary;
    @ViewInject(R.id.tv_weixian_pinggu)
    private TextView tv_weixian_pinggu;
    @ViewInject(R.id.tv_weixian_pinggu2)
    private TextView tv_weixian_pinggu2;
    @ViewInject(R.id.tv_talk_pinggu)
    private TextView tv_talk_pinggu;
    @ViewInject(R.id.tv_qingxu_pinggu)
    private TextView tv_qingxu_pinggu;

    private Gson mGson;
    private ContentSummaryAdapter mAdapter;

    //本条目数据
    private ContentSummaryIntentExtra mItem;
    //谈话配置
    private Rp_eduTypeArrList mEduTypeArrList;
    //当前选中 - 危险评估
    private Rp_eduType mSelectedDangerEvaluate;
    //当前选中 - 危险评估子项
    private Rp_eduType mSelectedDangerEvaluateSon;
    //当前选中 - 谈话评估
    private Rp_eduType mSelectedTalkEffect;
    //当前选中 - 情绪评估
    private Rp_eduType mSelectedEmotionEvaluate;
    //是否播放完成 1 完成
    private int mPlayPrecent = 0;
    /**
     * 播放相关--------
     */
    private AudioPlayer mAudioPlayer;
    private SimpleDateFormat mSdfMS;
    private Date tempDate;
    DecimalFormat mDecimalFormat;

    @Override
    protected void initData() {
        mGson = new Gson();
        mSdfMS = new SimpleDateFormat("mm:ss");
        tempDate = new Date();
        mDecimalFormat = new DecimalFormat("0.00");
        mAudioPlayer = new AudioPlayer(getApplicationContext(), mAudioHandler);
        mItem = (ContentSummaryIntentExtra) getIntent().getSerializableExtra(Constance.TO_PLAYMP3EVALUATE);
        //加载录音
        mAudioPlayer.loadUrl(mItem.getFile_path(), false);
        mAdapter = new ContentSummaryAdapter(this, new ArrayList<Rp_ContentSummary>());
        elv_content_summary.setAdapter(mAdapter);
        //去除父节点点击事件
        elv_content_summary.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        //防止空指针先实例化
        mEduTypeArrList = new Rp_eduTypeArrList();
        //TODO 从服务器获取数据
        getTalkType();
        getContentSummary();
    }

    @Event({R.id.iv_play, R.id.iv_pause, R.id.tv_weixian_pinggu, R.id.tv_weixian_pinggu2,
            R.id.tv_talk_pinggu, R.id.tv_qingxu_pinggu, R.id.btn_submit})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play:
                if (mAudioPlayer.getDuration() > 0) {//有时长说明加载成功 不需要重新加载
                    mAudioPlayer.playOrPause();
                    return;
                }
                mAudioPlayer.loadUrl(mItem.getFile_path(), true);
                break;
            case R.id.iv_pause:
                mAudioPlayer.playOrPause();
                break;

            case R.id.tv_weixian_pinggu://点击危险评估
                showPopWindow(mEduTypeArrList.getDanger_evaluate(), tv_weixian_pinggu);
                break;
            case R.id.tv_weixian_pinggu2://点击危险评估子项
                if (mSelectedDangerEvaluate == null) {
                    ToastUtils.showLong("请先选择危险评估");
                    return;
                }
                showPopWindow(mSelectedDangerEvaluate.getSub_data(), tv_weixian_pinggu2);
                break;
            case R.id.tv_talk_pinggu://点击谈话评估
                showPopWindow(mEduTypeArrList.getTalk_effect(), tv_talk_pinggu);
                break;
            case R.id.tv_qingxu_pinggu://点击情绪评估
                showPopWindow(mEduTypeArrList.getEmotion_evaluate(), tv_qingxu_pinggu);
                break;
            case R.id.btn_submit://提交
                afterSubmit();
                break;
        }
    }


    /**
     * 请求网络接口获取评价配置
     */
    private void getTalkType() {
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_EDUTALK_LOAD_TYPE, talkTypeCallBack);
    }

    /**
     * 获取评价配置接口回调
     */
    private CustomNetCallBack talkTypeCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            mEduTypeArrList = mGson.fromJson(data, Rp_eduTypeArrList.class);
            if (mEduTypeArrList == null) {
                ToastUtils.showLong("评价配置为空");
                return;
            }
            //获取配置成功后设置回显
            for (Rp_eduType danger_evaluate : mEduTypeArrList.getDanger_evaluate()) {
                if (danger_evaluate.getDisplay_value().equals(mItem.getDanger_evaluate())) {
                    tv_weixian_pinggu.setText(danger_evaluate.getDisplay_field());
                    mSelectedDangerEvaluate = danger_evaluate;

                    for (Rp_eduType danger_action : danger_evaluate.getSub_data()) {
                        if (danger_action.getDisplay_value().equals(mItem.getDanger_action())) {
                            tv_weixian_pinggu2.setText(danger_action.getDisplay_field());
                            mSelectedDangerEvaluateSon = danger_action;
                            break;
                        }
                    }
                    break;
                }
            }
            for (Rp_eduType emotion_evaluate : mEduTypeArrList.getEmotion_evaluate()) {
                if (emotion_evaluate.getDisplay_value().equals(mItem.getEmotion_evaluate())) {
                    tv_qingxu_pinggu.setText(emotion_evaluate.getDisplay_field());
                    mSelectedEmotionEvaluate = emotion_evaluate;
                    break;
                }
            }
            for (Rp_eduType talk_effect : mEduTypeArrList.getTalk_effect()) {
                if (talk_effect.getDisplay_value().equals(mItem.getTalk_effect())) {
                    tv_talk_pinggu.setText(talk_effect.getDisplay_field());
                    mSelectedTalkEffect = talk_effect;
                    break;
                }
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取谈话配置失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取谈话配置失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 调用接口获取内容概要
     */
    private void getContentSummary() {
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_EDUTALK_LOAD_CONTENT, getContentSummaryCallBack);
    }

    /**
     * 获取内容概要回调
     */
    private CustomNetCallBack getContentSummaryCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            List<Rp_ContentSummary> css = mGson.fromJson(data, new TypeToken<ArrayList<Rp_ContentSummary>>() {
            }.getType());
            mAdapter.setmList(css);
            expandGroup();
            if (css == null) {
                ToastUtils.showLong("服务器数据为空");
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取内容概要数据失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex);
            ToastUtils.showLong("获取内容概要数据失败");
        }
    };


    /**
     * 保存亲情会见亲情电话评价
     */
    private void afterSubmit() {
        if (mSelectedDangerEvaluate == null) {
            ToastUtils.showLong("请选择危险类别");
            return;
        }
        if (mSelectedDangerEvaluateSon == null) {
            ToastUtils.showLong("请选择危险详情");
            return;
        }
        if(!mSelectedDangerEvaluate.getDisplay_value().equals(mSelectedDangerEvaluateSon.getDisplay_value().substring(0,1))){
            ToastUtils.showLong("危险类别与危险详情不匹配");
            return;
        }
        if (mSelectedTalkEffect == null) {
            ToastUtils.showLong("请选择谈话评估");
            return;
        }
        if (mSelectedEmotionEvaluate == null) {
            ToastUtils.showLong("请选择情绪评估");
            return;
        }
        if (mAdapter.getCheckedList().size() < Constance.CONTENT_SUMMARY_MIN_SELECTED) {
            ToastUtils.showLong("至少选择"+Constance.CONTENT_SUMMARY_MIN_SELECTED+"项内容概要");
            return;
        }
        if (mPlayPrecent != 1) {
            ToastUtils.showLong("请先听完录音再提交评价");
            return;
        }

        if ((!Constance.DANGER_EVALUATE_OK.equals(mSelectedDangerEvaluate.getDisplay_value())) ||
                (!Constance.EMOTION_EVALUATE_OK.equals(mSelectedEmotionEvaluate.getDisplay_value())) ||
                (!Constance.TALK_EFFECT_OK.equals(mSelectedTalkEffect.getDisplay_value()))) {
            EduTalkTrackDialog dialog = new EduTalkTrackDialog(this, mEduTypeArrList.getStep_id());
            dialog.setOnClickListener(new EduTalkTrackDialog.OnClickListener() {
                @Override
                public void onPositive(List<Rp_eduType> listData) {
                    StringBuilder strs = new StringBuilder();
                    if (listData != null) {
                        for (Rp_eduType tempdata : listData) {
                            if (StringUtils.isEmpty(strs)) {
                                strs.append(tempdata.getDisplay_value());
                            } else {
                                strs.append("," + tempdata.getDisplay_value());
                            }
                        }
                    }
                    submitInterToSer(strs.toString());
                }
            }).show();
        } else {
            submitInterToSer("");
        }
    }


    /**
     * 调用接口提交谈话
     */
    private void submitInterToSer(String stepId) {
        Rq_saveEvaluation rq_se = new Rq_saveEvaluation();
        rq_se.setCus_number(MainApp.getInstance().getLoginUser().getCus_number() + "");
        rq_se.setRecord_id(mItem.getId() + "");
        rq_se.setType(mItem.getType() + "");
        rq_se.setPolice_id(MainApp.getInstance().getLoginUser().getPolice_id());
        rq_se.setPolice_name(MainApp.getInstance().getLoginUser().getPolice_name());
        rq_se.setDept_id(MainApp.getInstance().getLoginUser().getDepartment_id() + "");
        rq_se.setDept_name(MainApp.getInstance().getLoginUser().getDepartment_name());
        rq_se.setPrisoner_id(mItem.getPrisoner_id());
        rq_se.setPrisoner_name(mItem.getPrisoner_name());
        rq_se.setEvaluation("");
        rq_se.setRemark(mSelectedTalkEffect.getDisplay_field());
        rq_se.setPlay_percent(mPlayPrecent + "");
        rq_se.setTime(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        //12-28新加字段
        rq_se.setDanger_evaluate(mSelectedDangerEvaluate.getDisplay_value());
        rq_se.setDanger_action(mSelectedDangerEvaluateSon.getDisplay_value());
        rq_se.setEmotion_evaluate(mSelectedEmotionEvaluate.getDisplay_value());
        rq_se.setTalk_effect(mSelectedTalkEffect.getDisplay_value());
        rq_se.setVoice_content(mGson.toJson(mAdapter.getCheckedList()));
        //1-2新加字段
        rq_se.setStep_id(stepId);

        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_PHONE_SAVE_EVALUATION, rq_se, saveEvaluationCallback);
    }


    /**
     * 保存评价回调
     */
    private CustomNetCallBack saveEvaluationCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            ToastUtils.showLong("保存评价成功");
            LogUtils.e("保存评价成功");
            PlayMP3AndEvaluateActivity.this.finish();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("保存评价失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex.toString());
            ToastUtils.showLong("保存评价失败");
        }
    };


    /**
     * 播放回调处理
     */
    private Handler mAudioHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            playUIUpdate();
            switch (msg.what) {
                case AudioPlayer.HANDLER_CUR_TIME://当前播放状态时间
                    if (seekbarChangeLis.getState() == OnSeekBarChangedListener.DOWN) {
                        //如果是在滑动状态中则不设置
                        return;
                    }
                    //设置数字显示
                    tempDate.setTime((int) msg.obj);
                    tv_curPlayTime.setText(mSdfMS.format(tempDate));
                    //LogUtils.e(mSdfMS.format(tempDate));
                    //设置进度条显示
                    double play_percent = ((double) (int) msg.obj) / ((double) mAudioPlayer.getDuration());
                    int play_progress = (int) (Double.valueOf(mDecimalFormat.format(play_percent)) * 100);
                    pb_playPrecent.setProgress(play_progress);
                    break;
                case AudioPlayer.HANDLER_COMPLETE://播放完成
                    LogUtils.e("播放完成");
                    //播放完成时手动设置progress为100   防止出现progressbar填充不完整
                    pb_playPrecent.setProgress(100);
                    mPlayPrecent = 1;
                    break;
                case AudioPlayer.HANDLER_PREPARED://准备就绪
                    LogUtils.e("播放准备就绪");
                    int duation = (int) msg.obj;
                    String durationStr = new SimpleDateFormat("mm:ss").format(new Date(duation));
                    tv_durationTime.setText(durationStr);

                    //设置拖动监听
                    sb_playMp3.setOnSeekBarChangeListener(seekbarChangeLis);
                    break;
                case AudioPlayer.HANDLER_ERROR://播放出错
                    LogUtils.e("播放出错");
                    ToastUtils.showLong("播放文件出错");
                    mAudioPlayer.stop();
                    //播放文件出错时手动设置progress为0
                    pb_playPrecent.setProgress(0);
                    mPlayPrecent = 0;
                    break;
                case AudioPlayer.HANDLER_PAUSE://播放暂停
                    LogUtils.e("播放暂停");
                    //播放暂停取消拖动监听
                    //sb_playMp3.setOnSeekBarChangeListener(null);
                    break;
                case AudioPlayer.HANDLER_TOPLAY://继续播放
                    LogUtils.e("播放中……");
                    //播放时设置拖动监听
                    //sb_playMp3.setOnSeekBarChangeListener(seekbarChangeLis);
                    break;
            }
        }
    };


    /**
     * 进度条拖动监听
     */
    private OnSeekBarChangedListener seekbarChangeLis = new OnSeekBarChangedListener() {
        //百分比进度值 example:50（%）
        private double dbProgressPrecent;
        //改变之前的播放进度值 example:50 （%）
        private int intProgressAfterChanged;

        @Override
        public void progressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            //设置进度条
            dbProgressPrecent = (double) progress;
            pb_playPrecent.setProgress(progress);
            //设置数字显示
            double curtime = ((double) mAudioPlayer.getDuration()) * dbProgressPrecent / 100.0;
            String curtimeStr = mSdfMS.format(new Date((int) curtime));
            tv_curPlayTime.setText(curtimeStr);
        }

        @Override
        public void startTrackingTouch(SeekBar seekBar) {
            double tempDb = ((double) mAudioPlayer.getCurPosition()) / ((double) mAudioPlayer.getDuration());
            tempDb = Double.valueOf(mDecimalFormat.format(tempDb)) * 100;
            intProgressAfterChanged = (int) tempDb;
        }

        @Override
        public void stopTrackingTouch(SeekBar seekBar) {
            if (intProgressAfterChanged <= dbProgressPrecent) {
                //屏蔽往右拖动
                return;
            }
            mAudioPlayer.seekTo((int) (mAudioPlayer.getDuration() * dbProgressPrecent / 100.0));
        }
    };


    /**
     * 弹出选择项popwindow
     *
     * @param eduTypes
     * @param showAsDropDownView
     */
    private void showPopWindow(final List<Rp_eduType> eduTypes, final View showAsDropDownView) {
        if (eduTypes == null || eduTypes.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        EduUploadPopAdapter adapter = new EduUploadPopAdapter(this, eduTypes);
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(eduTypes.get(position).getDisplay_field());
                switch (showAsDropDownView.getId()) {
                    case R.id.tv_weixian_pinggu://点击危险评估
                        mSelectedDangerEvaluate = eduTypes.get(position);
                        mSelectedDangerEvaluateSon = null;
                        tv_weixian_pinggu2.setText("");
                        break;
                    case R.id.tv_weixian_pinggu2://点击危险评估子项
                        mSelectedDangerEvaluateSon = eduTypes.get(position);
                        break;
                    case R.id.tv_talk_pinggu://点击谈话评估
                        mSelectedTalkEffect = eduTypes.get(position);
                        break;
                    case R.id.tv_qingxu_pinggu://点击情绪评估
                        mSelectedEmotionEvaluate = eduTypes.get(position);
                        break;
                }
            }
        });
    }


    /**
     * 更新播放暂停按钮
     */
    private void playUIUpdate() {
        if (mAudioPlayer.getIsPlaying()) {
            iv_pause.setVisibility(View.VISIBLE);
            iv_play.setVisibility(View.GONE);
        } else {
            iv_play.setVisibility(View.VISIBLE);
            iv_pause.setVisibility(View.GONE);
        }
    }

    /*
     *全部展开
     */
    private void expandGroup() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < mAdapter.getmList().size(); i++) {
                    elv_content_summary.expandGroup(i);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        mAudioPlayer.stop();
        super.onDestroy();
    }
}
